﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using OpalisConsole.EndUserService;

namespace OpalisConsole.Views.User_Imaging
{
    public partial class Summary : Page
    {
        public Summary()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (App.Current.Resources["Computer_ID"].Equals("Not Approved"))
            {
                this.NavigationService.Navigate(new System.Uri("/User_Imaging/Unauthorized", System.UriKind.Relative));
            }
            else
            {
                txtSummaryMachineOnline.Text = "Machine Online";
                txtSummaryVPNConnection.Text = "Not Connected via VPN";
                txtSummaryWiredConnection.Text = "Wired Connection";
                txtSummaryACPower.Text = "AC Power";
                txtSummarySCCMAgent.Text = "SCCM Agent Healthy";

                DataAndSettingsRetention.Content = " *    Data and Settings Retained in Fresh Start Updated";
                VPNInstructions.Content = " *    New VPN Connection Instructions for Laptops";
                SelfInstallApp.Content = " *    Self-install Applications How To";
                Bitlocker.Content = " *    BitLocker Drive Encryption and You";
                getToKnowOffice.Content = " *    Get to Know Windows 7 and Office 2010";

                if (App.Current.Resources.Contains("DeveloperStatus"))
                {
                    if ((bool)App.Current.Resources["DeveloperStatus"]) { LinkUseUSMT.Visibility = System.Windows.Visibility.Visible; }
                }
                DateTime startTime = (DateTime)App.Current.Resources["ScheduledDate"];
               
                if (App.Current.Resources["Status"].Equals("Not Scheduled"))
                {
                    btnFinish.IsEnabled = true;
                    btnFinish.Visibility = System.Windows.Visibility.Visible;

                    btnPrevious.IsEnabled = true;
                    btnPrevious.Visibility = System.Windows.Visibility.Visible;

                    btnCancel.IsEnabled = true;
                    btnCancel.Visibility = System.Windows.Visibility.Collapsed;
                        
                    btnRecheck.IsEnabled = true;
                    btnRecheck.Visibility = System.Windows.Visibility.Collapsed;

                    txtSummaryHeader.Text = "Almost Done...";
                    txtSummaryContent.Text = "You are scheduling this computer [" + App.Current.Resources["ComputerName"].ToString() + "] a Fresh Start on " +
                                      startTime.ToLongDateString() + " at " + startTime.ToShortTimeString() + ".\n" +
                                      "\n" +
                                      "You will receive a calendar invite reminding you of this scheduled time.\n" +
                                      "Use the link in the calendar invitation to return to this site to cancel the Fresh Start process " +
                                      "if you need to \n" +
                                      "\n";

                    boxPreflighChecks.Text = "Click Schedule to complete your Fresh Start Request."; 
                }
                else
                {
                    btnFinish.IsEnabled = true;
                    btnFinish.Visibility = System.Windows.Visibility.Collapsed;

                    btnPrevious.IsEnabled = true;
                    btnPrevious.Visibility = System.Windows.Visibility.Collapsed;

                    btnCancel.IsEnabled = true;
                    btnCancel.Visibility = System.Windows.Visibility.Visible;

                    btnRecheck.IsEnabled = true;
                    btnRecheck.Visibility = System.Windows.Visibility.Visible;

                    txtSummaryHeader.Text = "Your Fresh Start is Scheduled";
                    txtSummaryContent.Text = "Your computer [" + App.Current.Resources["ComputerName"].ToString() + "] has a Fresh Start scheduled for " +
                                      startTime.ToLongDateString() + " at " + startTime.ToShortTimeString() + ".\n" +
                                      "\n" +
                                      "On the day of your scheduled update, return to this page (by typing “FreshStart” into the address " +
                                      "line in Internet Explorer) to confirm your computer is ready for the update. If you do not see all " +
                                      "green check marks on the ready list below, contact the Global Service Desk.\n" +
                                      "\n" +
                                      "Thank you for using the General Mills Fresh Start System";

                    txtPrepHeader.Text = "To prepare for your move to Windows 7, review the following links:";
                    
                    configureConnectionTestStart();
                    
                    EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                    proxy.InnerChannel.OperationTimeout = new TimeSpan(0, 30, 0);
                    proxy.checkACPoweredStatusCompleted += new EventHandler<checkACPoweredStatusCompletedEventArgs>(proxy_checkACPoweredStatusCompleted);
                    proxy.checkNotVPNConnectedStatusCompleted += new EventHandler<checkNotVPNConnectedStatusCompletedEventArgs>(proxy_checkNotVPNConnectedStatusCompleted);
                    proxy.checkPingStatusCompleted += new EventHandler<checkPingStatusCompletedEventArgs>(proxy_checkPingStatusCompleted);
                    proxy.checkSCCMClientHealthStatusCompleted += new EventHandler<checkSCCMClientHealthStatusCompletedEventArgs>(proxy_checkSCCMClientHealthStatusCompleted);
                    proxy.checkWiredConnectionStatusCompleted += new EventHandler<checkWiredConnectionStatusCompletedEventArgs>(proxy_checkWiredConnectionStatusCompleted);

                    string computerName = App.Current.Resources["ComputerName"].ToString();

                    proxy.checkACPoweredStatusAsync(computerName);
                    proxy.checkNotVPNConnectedStatusAsync(computerName);
                    proxy.checkPingStatusAsync(computerName);
                    proxy.checkSCCMClientHealthStatusAsync(computerName);
                    proxy.checkWiredConnectionStatusAsync(computerName);
                }
            }
        }

        void proxy_checkWiredConnectionStatusCompleted(object sender, checkWiredConnectionStatusCompletedEventArgs e)
        {
            spinnerWiredConnection.Visibility = System.Windows.Visibility.Collapsed;
            if (e.Result) { imgWiredConnectionSuccess.Visibility = System.Windows.Visibility.Visible; }
            else { imgWiredConnectionFailure.Visibility = System.Windows.Visibility.Visible; }
        }

        void proxy_checkSCCMClientHealthStatusCompleted(object sender, checkSCCMClientHealthStatusCompletedEventArgs e)
        {
            spinnerHealthySCCM.Visibility = System.Windows.Visibility.Collapsed;
            if (e.Result) { imgHealthySCCMSuccess.Visibility = System.Windows.Visibility.Visible; }
            else { imgHealthySCCMFailure.Visibility = System.Windows.Visibility.Visible; }
        }

        void proxy_checkPingStatusCompleted(object sender, checkPingStatusCompletedEventArgs e)
        {
            spinnerMachineOnline.Visibility = System.Windows.Visibility.Collapsed;
            if (e.Result) { imgMachineOnlineSuccess.Visibility = System.Windows.Visibility.Visible; }
            else { imgMachineOnlineFailure.Visibility = System.Windows.Visibility.Visible; }
        }

        void proxy_checkNotVPNConnectedStatusCompleted(object sender, checkNotVPNConnectedStatusCompletedEventArgs e)
        {
            spinnerNoVPN.Visibility = System.Windows.Visibility.Collapsed;
            if (e.Result) { imgNoVPNSuccess.Visibility = System.Windows.Visibility.Visible; }
            else { imgNoVPNFailure.Visibility = System.Windows.Visibility.Visible; }
        }

        void proxy_checkACPoweredStatusCompleted(object sender, checkACPoweredStatusCompletedEventArgs e)
        {
            spinnerACPower.Visibility = System.Windows.Visibility.Collapsed;
            if (e.Result) { imgACPowerSuccess.Visibility = System.Windows.Visibility.Visible; }
            else { imgACPowerFailure.Visibility = System.Windows.Visibility.Visible; }
        }
        private void btnPrevious_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new System.Uri("/User_Imaging/Scheduling", System.UriKind.Relative));
        }

        private void btnFinish_Click(object sender, RoutedEventArgs e)
        {
            DateTime UTCDateTime = ((DateTime)App.Current.Resources["ScheduledDate"]).ToUniversalTime();
            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            if (App.Current.Resources["Status"].Equals("Not Scheduled"))
            {
                proxy.createNewImagingRequestCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_createNewImagingRequestCompleted);

                if (App.Current.Resources.Contains("Data Choice"))
                {
                    proxy.createNewImagingRequestAsync(App.Current.Resources["ComputerName"].ToString(), App.Current.Resources["UserID"].ToString(), UTCDateTime, App.Current.Resources["Computer_ID"].ToString(), App.Current.Resources["FullUserID"].ToString(), App.Current.Resources["Data Choice"].ToString());
                }
                else
                {
                    proxy.createNewImagingRequestAsync(App.Current.Resources["ComputerName"].ToString(), App.Current.Resources["UserID"].ToString(), UTCDateTime, App.Current.Resources["Computer_ID"].ToString(), App.Current.Resources["FullUserID"].ToString(), "True");
                }
            }
            else
            {
                proxy.updateImagingRequestCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_updateImagingRequestCompleted_Update);
                proxy.updateImagingRequestAsync((string)App.Current.Resources["Imaging_ID"], UTCDateTime, "Cancelled");
            }
        }

        void proxy_updateImagingRequestCompleted_Update(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                FinishedWindow window = new FinishedWindow("There was an error updating your request. Please try again later");
                window.Show();
            }
            else
            {
                DateTime UTCDateTime = ((DateTime)App.Current.Resources["ScheduledDate"]).ToUniversalTime();
                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.createNewImagingRequestCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_createNewImagingRequestCompleted_Update);
                if (App.Current.Resources.Contains("Data Choice"))
                {
                    proxy.createNewImagingRequestAsync(App.Current.Resources["ComputerName"].ToString(), App.Current.Resources["UserID"].ToString(), UTCDateTime, App.Current.Resources["Computer_ID"].ToString(), App.Current.Resources["FullUserID"].ToString(), App.Current.Resources["Data Choice"].ToString());
                }
                else
                {
                    proxy.createNewImagingRequestAsync(App.Current.Resources["ComputerName"].ToString(), App.Current.Resources["UserID"].ToString(), UTCDateTime, App.Current.Resources["Computer_ID"].ToString(), App.Current.Resources["FullUserID"].ToString(), "True");
                }
            }
        }

        void proxy_createNewImagingRequestCompleted_Update(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                FinishedWindow window = new FinishedWindow("There was an error submitting your request. Please try again later");
                window.Show();
            }
            else
            {
                FinishedWindow window = new FinishedWindow("Your re-imaging request has been successfully Updated");
                window.Show();
                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.getRequestStatusCompleted += new EventHandler<getRequestStatusCompletedEventArgs>(proxy_getRequestStatusCompleted);
                proxy.getRequestStatusAsync((string)App.Current.Resources["ComputerName"]);
            }
        }

        void proxy_createNewImagingRequestCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                FinishedWindow window = new FinishedWindow("There was an error submitting your request. Please try again later");
                window.Show();
            }
            else
            {
                FinishedWindow window = new FinishedWindow("Your Windows 7 Fresh Start request has been successfully submitted");
                window.Show();

                EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
                proxy.getRequestStatusCompleted += new EventHandler<getRequestStatusCompletedEventArgs>(proxy_getRequestStatusCompleted);
                proxy.getRequestStatusAsync((string)App.Current.Resources["ComputerName"]);
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            proxy.updateImagingRequestCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(proxy_updateImagingRequestCompleted_Cancel);
            proxy.updateImagingRequestAsync((string)App.Current.Resources["Imaging_ID"], (DateTime)App.Current.Resources["ScheduledDate"], "Cancelled");
        }

        void proxy_updateImagingRequestCompleted_Cancel(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                FinishedWindow window = new FinishedWindow("There was an error updating your request. Please try again later");
                window.Show();
            }
            else
            {
                FinishedWindow window = new FinishedWindow("Your Windows 7 Fresh Start request has been successfully Cancelled");
                window.Show();
                App.Current.Resources.Remove("Status");
                App.Current.Resources.Add("Status", "Not Scheduled");
                App.Current.Resources.Remove("ScheduledDate");
                App.Current.Resources.Add("ScheduledDate", DateTime.Now.AddHours(1).Subtract(new TimeSpan(0, DateTime.Now.Minute, 0)));
                this.NavigationService.Navigate(new System.Uri("/User_Imaging/LandingPage", System.UriKind.Relative));
            }
        }

        void proxy_getRequestStatusCompleted(object sender, getRequestStatusCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                throw new Exception();
            }
            else
            {
                String result = e.Result.ToString();
                if (result.Equals("Not Scheduled"))
                {
                    this.Resources.Add("Status", "Not Scheduled");
                }
                else
                {
                    String Imaging_ID = result.Split(',')[0];
                    String OSDComputerName = result.Split(',')[1];
                    String Status = result.Split(',')[2];
                    DateTime StartDateTime = Convert.ToDateTime(result.Split(',')[3]).ToLocalTime();

                    App.Current.Resources.Remove("Status");
                    App.Current.Resources.Add("Status", Status);
                    App.Current.Resources.Remove("ScheduledDate");
                    App.Current.Resources.Add("ScheduledDate", StartDateTime);
                    App.Current.Resources.Remove("Imaging_ID");
                    App.Current.Resources.Add("Imaging_ID", Imaging_ID);
                }
                this.NavigationService.Navigate(new System.Uri("/Home", System.UriKind.Relative));
            }
        }

        private void gridSoftwareValidation_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            DataGridRow row = e.Row;
            SoftwareData data = (SoftwareData)row.DataContext;
            if (data.Status.Equals("Not Compatible"))
            {
                e.Row.Foreground = new SolidColorBrush(Colors.Red);
            }
            else
            {
                e.Row.Foreground = new SolidColorBrush(Colors.Black);
            }
        }

        private void btnRecheck_Click(object sender, RoutedEventArgs e)
        {
            configureConnectionTestStart();
            EndUserServiceSoapClient proxy = new EndUserServiceSoapClient();
            proxy.InnerChannel.OperationTimeout = new TimeSpan(0, 30, 0);
            proxy.checkACPoweredStatusCompleted += new EventHandler<checkACPoweredStatusCompletedEventArgs>(proxy_checkACPoweredStatusCompleted);
            proxy.checkNotVPNConnectedStatusCompleted += new EventHandler<checkNotVPNConnectedStatusCompletedEventArgs>(proxy_checkNotVPNConnectedStatusCompleted);
            proxy.checkPingStatusCompleted += new EventHandler<checkPingStatusCompletedEventArgs>(proxy_checkPingStatusCompleted);
            proxy.checkSCCMClientHealthStatusCompleted += new EventHandler<checkSCCMClientHealthStatusCompletedEventArgs>(proxy_checkSCCMClientHealthStatusCompleted);
            proxy.checkWiredConnectionStatusCompleted += new EventHandler<checkWiredConnectionStatusCompletedEventArgs>(proxy_checkWiredConnectionStatusCompleted);
            
            string computerName = App.Current.Resources["ComputerName"].ToString();

            proxy.checkACPoweredStatusAsync(computerName);
            proxy.checkNotVPNConnectedStatusAsync(computerName);
            proxy.checkPingStatusAsync(computerName);
            proxy.checkSCCMClientHealthStatusAsync(computerName);
            proxy.checkWiredConnectionStatusAsync(computerName);
        }

        private void configureConnectionTestStart()
        {
            panelPreFlight.Visibility = System.Windows.Visibility.Visible;

            spinnerACPower.Visibility = System.Windows.Visibility.Visible;
            imgACPowerFailure.Visibility = System.Windows.Visibility.Collapsed;
            imgACPowerSuccess.Visibility = System.Windows.Visibility.Collapsed;

            spinnerHealthySCCM.Visibility = System.Windows.Visibility.Visible;
            imgHealthySCCMFailure.Visibility = System.Windows.Visibility.Collapsed;
            imgHealthySCCMSuccess.Visibility = System.Windows.Visibility.Collapsed;

            spinnerMachineOnline.Visibility = System.Windows.Visibility.Visible;
            imgMachineOnlineFailure.Visibility = System.Windows.Visibility.Collapsed;
            imgMachineOnlineSuccess.Visibility = System.Windows.Visibility.Collapsed;

            spinnerNoVPN.Visibility = System.Windows.Visibility.Visible;
            imgNoVPNFailure.Visibility = System.Windows.Visibility.Collapsed;
            imgNoVPNSuccess.Visibility = System.Windows.Visibility.Collapsed;

            spinnerWiredConnection.Visibility = System.Windows.Visibility.Visible;
            imgWiredConnectionFailure.Visibility = System.Windows.Visibility.Collapsed;
            imgWiredConnectionSuccess.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void getToKnowOffice_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("http://spis.generalmills.com/sites/mshub/Pages/Product.aspx?Product=StartHere"), "_newWindow");
        }

        private void Bitlocker_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("https://champions.generalmills.com/gmispservices/gmigetspdoc/getdoc.ashx?doc=10336460"), "_newWindow");
        }

        private void SelfInstallApp_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("https://champions.generalmills.com/gmispservices/gmigetspdoc/getdoc.ashx?doc=10511966"), "_newWindow");
        }

        private void VPNInstructions_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("https://champions.generalmills.com/gmispservices/gmigetspdoc/getdoc.ashx?doc=10337971"), "_newWindow");
        }

        private void DataAndSettingsRetention_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("https://champions.generalmills.com/gmispservices/gmigetspdoc/getdoc.ashx?doc=10338750"), "_newWindow");
        }
    }
}
